# -*- coding: utf-8 -*-
import os
import subprocess
import time
import re


class Shell:
    @staticmethod
    def invoke(args,filename=None):
        """
        shell设为true，程序将通过shell来执行
        stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。
        他们可以是PIPE，文件描述符或文件对象，也可以设置为None，表示从父进程继承。
        subprocess.PIPE实际上为文本流提供一个缓存区
        input_cmd=args.strip().split()
        """
        output, errors = subprocess.Popen(args.strip(), shell=True, stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE).communicate()
        o = output.decode("utf-8", "ignore") + errors.decode("utf-8", "ignore")
        return o.strip()


class testlog(object):
    def __init__(self):
        print('测试开始')
        if os.path.exists('result.txt'):
            os.remove('result.txt')
        count = 1
        while True:
            with open('result.txt','a') as file:
                print(f'次数:{count}')
                file.write(f'次数:{count}\n')
                count += 1
                testtime=time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                print(f'时间:{testtime}')
                file.write(f'时间:{testtime}')
                if not self.test():
                    print('------------测试出现异常，脚本停止')
                    file.write('------------测试出现异常，脚本停止')
                    break


    def test(self):
        shell = Shell()
        flag=False
        testlog=None
        for i in range(10):
            time.sleep(5)
            testlog = shell.invoke('adb wait-for-device logcat -t 20000')
            for line in testlog.splitlines():
                #if re.findall('', line):
                if 'getmetas' in line:
                    flag = True
                    print(line)
                    break
            if flag:
                print(f'------------测试结果{flag}')
                shell.invoke('adb wait-for-device reboot')
                return True
        with open('error_log.txt','w') as file:
            file.write(testlog)
        shell.invoke('adb wait-for-device reboot')
        return False



testlog().test()
